/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2022-09-21
 * Time: 19:07
 */
public class MyLinkList {
    static class ListNode {
        public int val;
        public ListNode prev;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;//标记双向链表的头部
    public ListNode tail;//标记双向链表的尾部

    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        if (this.head == null) {
            this.head = node;
            this.tail = node;
        } else {
            node.next = this.head;
            this.head.prev = node;
            head = node;
        }
    }

    public void addLast(int data) {
        ListNode node = new ListNode(data);
        if (this.head == null) {
            this.head = node;
            this.tail = node;
        } else {
            this.tail.next = node;
            node.prev = this.tail;
            this.tail = node;
        }
    }

    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index,int data){
        ListNode node = new ListNode(data);
        //1、判断Index位置的合法性
        if (index < 0 || index >= size()) {
            System.out.println("坐标不合法");
            throw new IndexWrongFulException("坐标不合法");
        }
        //2、判断特殊位置，头插 和 尾插
        if (index == 0) {
            addFirst(data);
            return;
        }
        if (index == size()-1) {
            addLast(data);
            return;
        }
        //3、找到index位置节点的地址
        ListNode cur = findIndexListNode(index);
        node.next = cur;
        node.prev = cur.prev;
        cur.prev.next = node;
        cur.prev = node;

    }

    public void clear(){
        ListNode cur = head;
        while (cur != tail) {
            ListNode curNext = cur.next;
            cur.prev = null;
            cur.next = null;
            cur = curNext;
        }
        head = null;
        tail = null;
    }

    private ListNode findIndexListNode(int index) {
        ListNode cur = this.head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        return cur;
    }
}
